package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.interceptor.UserHolder;
import org.example.mapper.WmNewsMapper;
import org.example.pojo.entity.ApLove;
import org.example.mapper.ApLoveMapper;
import org.example.pojo.entity.WmNews;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.service.IApLoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-02-04
 */
@Service
public class ApLoveServiceImpl extends ServiceImpl<ApLoveMapper, ApLove> implements IApLoveService {


    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public void like(String articleId) {
        //判断是否已经点赞
        QueryWrapper<ApLove> wrapper = new QueryWrapper();
        wrapper.eq("article_id", articleId);
        wrapper.eq("love_user_id", UserHolder.getUserId());
        ApLove love = baseMapper.selectOne(wrapper);
        if (love == null) {
            ApLove apLove = new ApLove();
            apLove.setLoveUserId(UserHolder.get().getId());
            apLove.setArticleId(Integer.valueOf(articleId));
            apLove.setCreateTime(LocalDateTime.now());
            baseMapper.insert(apLove);
        }
    }

    @Override
    public void unlike(String articleId) {
        //判断是否已经点赞
        QueryWrapper<ApLove> wrapper = new QueryWrapper();
        wrapper.eq("article_id", articleId);
        wrapper.eq("love_user_id", UserHolder.getUserId());
        ApLove love = baseMapper.selectOne(wrapper);
        if (love != null) {
            baseMapper.delete(wrapper);
        }


    }

    @Override
    public List<WmNews> likeArticle() {
        List<ApLove> collectUserId = baseMapper.selectList(new QueryWrapper<ApLove>().eq("love_user_id", UserHolder.get().getId()));
        //获取文章id
        List<Integer> articleIds = collectUserId.stream().map(ApLove::getArticleId).collect(Collectors.toList());
        return wmNewsMapper.selectBatchIds(articleIds);
    }

    @Override
    public Long islike(String articleId) {
        QueryWrapper<ApLove> wrapper = new QueryWrapper();
        wrapper.eq("article_id", articleId);
        wrapper.eq("love_user_id", UserHolder.get().getId());
        return baseMapper.selectCount(wrapper);
    }


}
